package nju.software.tagmanager.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import nju.software.tagmanager.common.constant.MessageConstant;
import nju.software.tagmanager.common.context.BaseContext;
import nju.software.tagmanager.common.exception.CategoryAlreadyExistsException;
import nju.software.tagmanager.common.result.Result;
import nju.software.tagmanager.pojo.dto.CategoryPageQueryDTO;
import nju.software.tagmanager.pojo.dto.TagPageQueryDTO;
import nju.software.tagmanager.pojo.entity.Category;
import nju.software.tagmanager.pojo.entity.RelCategoryTag;
import nju.software.tagmanager.pojo.entity.Tag;
import nju.software.tagmanager.pojo.vo.CategoryVO;
import nju.software.tagmanager.pojo.vo.TagVO;
import nju.software.tagmanager.service.CategoryService;
import nju.software.tagmanager.service.RelCategoryTagService;
import nju.software.tagmanager.service.RelTagItemService;
import nju.software.tagmanager.service.TagService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author: raychou
 * @date: 2024-01-14 21:53
 * @description:
 */
@Api(tags = "类别标签模块接口")
@RestController
@RequestMapping("/category-tag")
@Slf4j
public class CategoryTagController {

    @Resource
    private CategoryService categoryService;
    @Resource
    private TagService tagService;

    @Resource
    private RelCategoryTagService relCategoryTagService;

    @ApiOperation("分页查询类别")
    @PostMapping("/category-list")
    public Result<JSONObject> categoryList(@RequestBody CategoryPageQueryDTO query) {
        IPage<CategoryVO> result = categoryService.search(query);
        JSONObject data = new JSONObject();
        data.put("total", result.getTotal());
        data.put("records", result.getRecords());
        return Result.success("查询类别成功", data);
    }

    @ApiOperation("分页查询标签")
    @PostMapping("/tag-list")
    public Result<JSONObject> tagList(@RequestBody TagPageQueryDTO query) {
        IPage<TagVO> result = tagService.search(query);
        JSONObject data = new JSONObject();
        data.put("total", result.getTotal());
        data.put("records", result.getRecords());
        return Result.success("查询标签成功", data);
    }

    @ApiOperation("将指定标签从指定类别中删除")
    @PostMapping("/remove-tag-from-category")
    public Result<Object> removeTagFromCategory(@RequestParam("tagId") Integer tagId, @RequestParam("categoryId") Integer categoryId) {
        boolean removed = relCategoryTagService.remove(new QueryWrapper<RelCategoryTag>()
                .eq("tag_id", tagId)
                .eq("category_id", categoryId));
        if (!removed) {
            log.error("删除失败:{ tagId:{}, categoryId:{} }", tagId, categoryId);
            return Result.error(MessageConstant.DELETE_FAILURE);
        }
        return Result.success(MessageConstant.DELETE_SUCCESS, null);
    }

    @ApiOperation("将指定标签加入指定类别")
    @PostMapping("/add-tag-to-category")
    public Result<Object> addTagToCategory(@RequestParam("tagId") Integer tagId, @RequestParam("categoryId") Integer categoryId) {
        relCategoryTagService.addTagToCategory(tagId, categoryId);
        return Result.success("标签加入类别成功");
    }

    @ApiOperation("新增标签并加入指定类别")
    @PostMapping("/add-new-tag-by-category-id")
    public Result<Object> addNewTagByCategoryId(@RequestParam("tagName") String tagName, @RequestParam("categoryId") Integer categoryId) {
        tagService.addTagByCategoryId(tagName, categoryId);
        return Result.success("新增标签并加入类别成功");
    }

    @ApiOperation("根据标签名找到所有匹配的标签")
    @PostMapping("/find-tags-by-name")
    public Result<List<Tag>> findTagsByName(@RequestParam("tagName") String tagName) {
        return Result.success(tagService.list(new QueryWrapper<Tag>().like("name", tagName)));
    }

    @ApiOperation("根据类别名找到所有匹配的类别")
    @PostMapping("/find-categories-by-name")
    public Result<List<Category>> findCategoriesByName(@RequestParam("categoryName") String categoryName) {
        return Result.success(categoryService.list(new QueryWrapper<Category>().like("name", categoryName)));
    }

    @ApiOperation("删除标签")
    @PostMapping("/delete-tag-by-id")
    public Result<Object> deleteTagById(@RequestParam("tagId") Integer tagId) {

        tagService.deleteById(tagId);
        return Result.success(MessageConstant.DELETE_SUCCESS, null);
    }


    @ApiOperation("添加类别")
    @PostMapping("/add-category")
    public Result<Object> addCategory(@RequestParam("categoryName") String categoryName) {
        List<Category> exists = categoryService.list(new QueryWrapper<Category>().eq("name", categoryName));
        if (exists != null && !exists.isEmpty()) {
            throw new CategoryAlreadyExistsException();
        }
        Category category = Category.builder()
                .name(categoryName)
                .createUserId(BaseContext.getCurrentUserId())
                .build();

        categoryService.save(category);
        return Result.success("添加类别成功", null);
    }

    @ApiOperation("找到只从属于特定类别的标签")
    @PostMapping("/find-tags-only-following")
    public Result<List<TagVO>> findTagsOnlyFollowing(@RequestParam("categoryId") Integer categoryId) {
        List<TagVO> tags = tagService.findOnlyFollowing(categoryId);
        return Result.success("查询成功", tags);
    }

    @ApiOperation("根据id删除类别，并级联删除只从属于它的标签")
    @PostMapping("/delete-category-cascade-by-id")
    public Result<Object> deleteCategoryCascade(@RequestParam("categoryId") Integer categoryId) {
        categoryService.deleteCascadeById(categoryId);
        return Result.success(MessageConstant.DELETE_SUCCESS, null);
    }

    @ApiOperation("找到只从属于特定类别的标签")
    @PostMapping("/delete-category-by-id")
    public Result<Object> deleteCategory(@RequestParam("categoryId") Integer categoryId) {
        categoryService.deleteById(categoryId);

        return Result.success(MessageConstant.DELETE_SUCCESS, null);
    }

    @ApiOperation("根据类别id更新备注")
    @PostMapping("/update-comment-by-category-id")
        public Result<Object> updateCommentByCategoryId(@RequestParam("categoryId") Integer categoryId,
                                                         @RequestParam("comment") String comment) {
        Category category = Category.builder()
                .id(categoryId)
                .comment(comment)
                .build();
        categoryService.updateById(category);
        return Result.success(MessageConstant.COMMENT_UPDATE_SUCCESS, null);
    }

    @ApiOperation("根据标签id更新备注")
    @PostMapping("/update-comment-by-tag-id")
    public Result<Object> updateCommentByTagId(@RequestParam("tagId") Integer tagId,
                                                    @RequestParam("comment") String comment) {
        Tag tag = Tag.builder()
                .id(tagId)
                .comment(comment)
                .build();

        tagService.updateById(tag);
        return Result.success(MessageConstant.COMMENT_UPDATE_SUCCESS, null);
    }


}
